<template>
  <div>
    <div ref="titlePane" style="display: flex; flex-direction: row-reverse; padding: .5rem ; position: fixed; left: 0; right: 0; top: 0; z-index: 100; background-color: #FFF;">
      <Button ref="selectBtn" class="del-btn" @click="selectFile" v-show="!processing">
        <svg t="1650979804340" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1883" width="20" height="20"><path d="M514.048 62.464q93.184 0 175.616 35.328t143.872 96.768 96.768 143.872 35.328 175.616q0 94.208-35.328 176.128t-96.768 143.36-143.872 96.768-175.616 35.328q-94.208 0-176.64-35.328t-143.872-96.768-96.768-143.36-35.328-176.128q0-93.184 35.328-175.616t96.768-143.872 143.872-96.768 176.64-35.328zM772.096 576.512q26.624 0 45.056-18.944t18.432-45.568-18.432-45.056-45.056-18.432l-192.512 0 0-192.512q0-26.624-18.944-45.568t-45.568-18.944-45.056 18.944-18.432 45.568l0 192.512-192.512 0q-26.624 0-45.056 18.432t-18.432 45.056 18.432 45.568 45.056 18.944l192.512 0 0 191.488q0 26.624 18.432 45.568t45.056 18.944 45.568-18.944 18.944-45.568l0-191.488 192.512 0z" p-id="1884" fill="#0e932e"></path></svg>
      </Button>
      <canvas ref="processCanvas" width="20" height="20" v-show="processing"/>
      <Button class="del-btn"  v-if="player.level == 3" @click="closeProcessingMusic">
        <svg t="1651243445882" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2074" width="20" height="20"><path d="M512 42.666667C252.793333 42.666667 42.666667 252.793333 42.666667 512s210.126667 469.333333 469.333333 469.333333 469.333333-210.126667 469.333333-469.333333S771.206667 42.666667 512 42.666667z m213.333333 645.333333a37.373333 37.373333 0 0 1-37.333333 37.333333H336a37.373333 37.373333 0 0 1-37.333333-37.333333V336a37.373333 37.373333 0 0 1 37.333333-37.333333h352a37.373333 37.373333 0 0 1 37.333333 37.333333z" fill="#d81e06" p-id="2075"></path></svg>
      </Button>
      <span v-if="player.level == 2 || player.level == 3" style="font-weight: bold; color: #8c8c8c; font-size: .8rem; overflow: hidden; text-overflow: ellipsis;  word-wrap: normal; white-space: nowrap;"><span v-if="player.level == 2" style="color: #E757CD;">闹铃正在蜂鸣，无法播放音乐，稍后会播放您选择的音乐</span><span v-if="player.name && player.name.length > 0" style="color:#00d977;">正在播放:</span><span style="overflow: hidden; text-overflow: ellipsis;">{{player.name}}</span></span>
      <input type="file" ref="fileInput" style="display: none;" accept="audio/mpeg" @change="afterSelectFile"/>
    </div>
    <div class="music-content" :style="'top:'+musicContentTop+'px;'">
      <ul class="music-list">
        <li v-for="m in musicList" :key="m" @click="playMusic(m.audioPath)">
          <div class="li-box" style="position: relative;">
            <span style="display: flex; align-items: center;"><span :style="'background-color:'+ m.color+';'" class="file-suffix">{{m.suffix}}</span><span style=" overflow: hidden; text-overflow: ellipsis;">{{m.audioName}}</span></span>
            <Button class="del-btn" @click.stop="delMusic(m.audioPath)">
              <svg t="1650695525843" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4099" width="20" height="20"><path d="M989.866667 238.933333A102.4 102.4 0 0 0 887.466667 136.533333h-107.861334v-34.133333A102.4 102.4 0 0 0 677.205333 0h-341.333333a102.4 102.4 0 0 0-102.4 102.4V136.533333H136.533333A102.4 102.4 0 0 0 102.4 335.189333V887.466667a136.533333 136.533333 0 0 0 136.533333 136.533333h546.133334a136.533333 136.533333 0 0 0 136.533333-136.533333V335.189333a102.4 102.4 0 0 0 68.266667-96.256z m-688.128-136.533333a34.133333 34.133333 0 0 1 34.133333-34.133333h341.333333a34.133333 34.133333 0 0 1 34.133334 34.133333V136.533333h-409.6zM853.333333 887.466667a68.266667 68.266667 0 0 1-68.266666 68.266666H238.933333a68.266667 68.266667 0 0 1-68.266666-68.266666V341.333333h682.666666z m34.133334-614.4h-750.933334a34.133333 34.133333 0 0 1 0-68.266667h750.933334a34.133333 34.133333 0 0 1 0 68.266667z" fill="#d81e06" p-id="4100"></path><path d="M341.333333 836.266667a34.133333 34.133333 0 0 0 34.133334-34.133334v-307.2a34.133333 34.133333 0 0 0-68.266667 0v307.2a34.133333 34.133333 0 0 0 34.133333 34.133334zM512 836.266667a34.133333 34.133333 0 0 0 34.133333-34.133334v-307.2a34.133333 34.133333 0 0 0-68.266666 0v307.2a34.133333 34.133333 0 0 0 34.133333 34.133334zM682.666667 836.266667a34.133333 34.133333 0 0 0 34.133333-34.133334v-307.2a34.133333 34.133333 0 0 0-68.266667 0v307.2a34.133333 34.133333 0 0 0 34.133334 34.133334z" fill="#d81e06" p-id="4101"></path></svg>
            </Button>
          </div>
        </li>
      </ul>
    </div>
  </div>
</template>
<script>
import {reactive} from "vue";
import request from "@/requestutil";

export default {
  name : "MusicList",
  components: {
  },
  data() {
    return {
      musicList: reactive([]),
      musicContentTop:0,
      processing: false,
      ctx: null,
      lineStyle: null,

      player: {}
    }
  },
  mounted() {
    this.musicContentTop = this.$refs.titlePane.clientHeight
    this.$refs.processCanvas.width = this.$refs.selectBtn.clientWidth
    this.$refs.processCanvas.height = this.$refs.selectBtn.clientHeight
    this.refresh()

    let ctx = this.$refs.processCanvas.getContext('2d')
    var lineargradient = ctx.createLinearGradient(0, 0, 20, 0)
    lineargradient.addColorStop(0, 'rgb(0,176,30)')
    lineargradient.addColorStop(0.5, 'rgb(253,127,0)')
    lineargradient.addColorStop(1, 'rgb(222,0,0)')
    this.lineStyle = lineargradient
    this.ctx = ctx

    if (!window.stateWatcher) {
      window.stateWatcher={}
    }
    window.stateWatcher.showMusic = true
    let self = this
    window.stateWatcher.musicWatcher = function (overrideSecond){
      if (!window.stateWatcher.showMusic) {
        return
      }
      let second
      if (overrideSecond !== undefined) {
        second = overrideSecond
      } else {
        second = 1
      }
      let musicId = setTimeout(()=>{
        if (window.stateWatcher.musicProcessWatcherId === musicId) {
          request.get('/api/music/current')
              .then(r=>{
                if (r.data.code == 1) {
                  let clockInfo = r.data.data
                  console.log(clockInfo)
                  if (clockInfo) {
                    if (clockInfo.level == 3) {
                      self.player.name = clockInfo.name
                    } else {
                      self.player.name = ''
                    }
                    self.player.level = clockInfo.level
                    window.stateWatcher.musicWatcher(1)
                    return
                  }
                }
                if (self.player.level) {
                  self.player.name = ''
                  self.player.level = 0
                }
                window.stateWatcher.musicWatcher()
              })
              .catch(()=>{
                if (self.player.level) {
                  self.player.name = ''
                  self.player.level = 0
                }
                window.stateWatcher.musicWatcher()
              })
        }
      }, second <= 0 ? 10 : second * 1000)
      window.stateWatcher.musicProcessWatcherId = musicId
    }
    window.stateWatcher.musicWatcher(0)
  },
  beforeUnmount() {
    window.stateWatcher.showMusic = false
    let musicProcessWatcherId = window.stateWatcher.musicProcessWatcherId
    if (musicProcessWatcherId) {
      window.clearTimeout(musicProcessWatcherId)
    }
  },
  methods: {
    refresh() {
      request.get('/api/music/list')
          .then(r=>{
            let data =r.data
            if (data.code == 1) {
              let list = data.data
              if (list) {
                for (let i=0; i<list.length; i++) {
                  if (list[i].suffix === 'ogg') {
                    list[i].color = '#e757cd'
                  } else if (list[i].suffix === 'mp3') {
                    list[i].color = '#53d3cc'
                  } else if (list[i].suffix === 'flac') {
                    list[i].color = '#F3A553'
                  } else if (list[i].suffix === 'wav') {
                    list[i].color = '#59A8EC'
                  } else {
                    if (!list[i].suffix || list[i].suffix.length === 0) {
                      list[i].suffix = '未知'
                    }
                    list[i].color = '#ff5c5c'
                  }
                }
              }
              this.musicList = list
            }
          })
    },
    delMusic(path) {
      let self = this
      request.post('/api/file_manager/delete-file', {path})
      .then(r=>{
        let data =r.data
        if (data.code == 1) {
          window.openMsg('删除成功',true)
          self.refresh()
        } else {
          window.openMsg(data.msg||'删除失败')
        }
      })
    },
    selectFile() {
      this.$refs.fileInput.click()
    },
    //关闭音乐
    closeProcessingMusic() {
      request.get('/api/music/close/3')
          .then(r=>{
            if (r.data.code != 1) {
              window.openMsg('操作失败')
            }
          })
    },
    playMusic(audioPath) {
      request.post('/api/music/play',{audioPath})
      .then(r=>{
        if (r.data.code != 1) {
          window.openMsg('操作失败')
        }
      })
    },
    afterSelectFile(event) {
      let self = this
      let files = event.target.files
      if (files && files.length > 0) {
        self.processing = true
        let file = files[0]
        request.post('/api/file_manager/check-exists', {fileName: file.name})
        .then(r=>{
          let data =r.data
          if (data.code != 1) {
            self.processing = false
            window.openMsg(data.msg||'上传失败')
            return
          } else if (data.data) {
            self.processing = false
            window.openMsg('此文件已存在，无需上传')
            return
          }
          doUpload(self, file)
        }).catch(()=>{
          self.processing = false
        })
        event.target.value=''
      }
    }
  }
}

function doUpload(self, file) {
  var form = new window.FormData()
  form.append('file',file)
  var xhr = new window.XMLHttpRequest()
  xhr.open('post', '/api/file_manager/upload', true)
  xhr.upload.addEventListener(
      'progress',
      function (result) {
        if (result.lengthComputable) {
          //上传进度
          var percent = result.loaded / result.total

          let ctx = self.ctx
          ctx.clearRect(0,0,self.$refs.processCanvas.width, self.$refs.processCanvas.height)

          ctx.beginPath()
          ctx.arc(10,10,10,Math.PI * 1.5, Math.PI * 3.5,false)
          ctx.lineTo(10, 10)
          ctx.closePath()
          ctx.fillStyle='rgb(0,176,30)'
          ctx.fill()

          ctx.beginPath()
          ctx.arc(10,10,8,Math.PI * 1.5, Math.PI * 3.5,false)
          ctx.lineTo(10, 10)
          ctx.closePath()
          ctx.fillStyle='white'
          ctx.fill()

          // 开始绘画
          ctx.beginPath()
          // 画圆的函数，四个参数分别为x, y（坐标）, radius（半径）, angle（环形半径）, direction（环形方向，顺时针或者逆时针）
          // angle是我定义的一个变量，控制角度用的。一个完整的圆是Math.PI*2，angle把2均分之后的对应值
          //1.5 - 3.5
          ctx.arc(10, 10, 8, Math.PI * 1.5, Math.PI * (1.5 + 2 * percent), false)
          // 移动笔触到圆心
          ctx.lineTo(10, 10)
          // 闭合路径
          ctx.closePath()
          ctx.fillStyle = self.lineStyle
          ctx.fill()

          ctx.beginPath()
          ctx.arc(10,10,6,Math.PI * 1.5, Math.PI * 3.5,false)
          ctx.lineTo(10, 10)
          ctx.closePath()
          ctx.fillStyle='rgb(0,176,30)'
          ctx.fill()

          ctx.beginPath()
          ctx.arc(10,10,4,Math.PI * 1.5, Math.PI * 3.5,false)
          ctx.lineTo(10, 10)
          ctx.closePath()
          ctx.fillStyle='white'
          ctx.fill()

        }
      },
      false
  )
  xhr.addEventListener('readystatechange', function () {
    self.processing = false
    if (xhr.status != 200) {
      window.openMsg(file.name()+ ' 上传失败，返回code: '+xhr.status)
    } else if (xhr.readyState == 4) {
      var data = JSON.parse(xhr.responseText || xhr.response)
      if (data.code == 1) {
        self.refresh()
        window.openMsg(file.name+ '上传完成', true)
      } else {
        window.openMsg(file.name+' 暂不可上传：'+data.msg)
      }
    }
  })
  xhr.send(form)
}
</script>
<style lang="css" scoped>
.music-list>li {
  border-bottom: .01rem solid #EEE;
}
.music-list>li:active {
  background-color: #EEE;
}
.music-list>li .li-box {
  padding: .3rem 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.music-list .li-box >span{
  display: inline-block;
  overflow: hidden;
  text-overflow: ellipsis;
  text-wrap: normal;
  word-wrap: normal;
  white-space: nowrap;
}
.del-btn {
  width: 21px;
  height:21px;
  border-radius: 21px;
  padding:0;
  border:none;
}
.music-content {
  padding: 0 .5rem;
  position: relative;
  z-index: 99;
}
.file-suffix {
  color: #FFF;
  border-radius: .3rem;
  font-size: 0.5rem;
  padding: .1rem;
}
</style>